package com.mf.utils;

import com.mf.entity.CodeHistory;
import com.mf.vo.StockGatherVo;

import java.util.List;

/**
 * @Author: lmf
 * @Create: 2024/6/4 16:03
 * Description:
 */
public class MacdUtils {
    public static StockGatherVo calculateMacdAndDate (List<CodeHistory> codeHistoryList){
        int shortPeriod = 12;
        int longPeriod = 26;
        int signalPeriod = 9;

        int n = codeHistoryList.size();
        double[] shortEma = new double[n];
        double[] longEma = new double[n];
        double[] signalLine = new double[n];
        double[] macdLine = new double[n];
        double[] dif = new double[n];
        String[] date = new String[n];

        final double c = codeHistoryList.get(0).getC().doubleValue();
        // 计算短期（指数移动平均）
        shortEma[0] = c;
        // 计算长期的EMA（指数移动平均）
        longEma[0] = c;

        // 计算DEA (差离平均值)
        signalLine[0] = dif[0];
        for (int i = 1; i < n; i++) {
            double k = 2.0 / (shortPeriod + 1);
            final double p1 = codeHistoryList.get(i).getC().doubleValue();
            // 计算短期EMA
            shortEma[i] = (p1 - shortEma[i - 1]) * k + shortEma[i - 1];

            double k2 = 2.0 / (longPeriod + 1);
            // 计算长期的EMA
            longEma[i] = (p1 - longEma[i - 1]) * k2 + longEma[i - 1];

            //  计算DIF (差离值)
            dif[i] = shortEma[i] - longEma[i];

            // 计算DEA (差离平均值)
            double k3 = 2.0 / (signalPeriod + 1);
            signalLine[i] = (dif[i] - signalLine[i - 1]) * k3 + signalLine[i - 1];

            // 计算MACD线 (DIF - DEA)    * 2 --> 为了更好的展示
            macdLine[i] = (dif[i] - signalLine[i]) * 2;

            date[i] = codeHistoryList.get(i).getD();
        }
        // 创建结果列表
        StockGatherVo result = new StockGatherVo();
        result.setMacd(macdLine);
        result.setDif(dif);
        result.setDea(signalLine);
        result.setDate(date);
        result.setDm(codeHistoryList.get(0).getDm());
        return result;
    }
}
